package com.servlet;

import com.pojo.Person;
import com.util.BaseServlet;
import com.util.ResultData;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;

import static com.util.Vessel.personSer;

@WebServlet("/person")
public class PersonServlet extends BaseServlet {
    @Override
    public Class getServlet() {
        return PersonServlet.class;
    }

    public String queryPerson(HttpServletRequest request, HttpServletResponse response){
        List<Person> personList = personSer.queryPerson();
        HttpSession session = request.getSession();
        session.setAttribute("personList",personList);
        return "personList";
    }

    //删除
    public ResultData delPerson(HttpServletRequest request, HttpServletResponse response){
        int id = Integer.parseInt(request.getParameter("id"));
        int num = 0;
        Person person = new Person();
        person.setId(id);
        ResultData resultData = new ResultData();
        num = personSer.delPerson(person);
        if (num > 0){
            resultData.setMsg("删除成功");
        }
        return resultData;
    }

    //添加
    public void addPerson(HttpServletRequest request, HttpServletResponse response){
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String ageStr = request.getParameter("age");
        int age = Integer.parseInt(ageStr);
        String rank = request.getParameter("rank");
        String department = request.getParameter("department");
        Person person = new Person();
        person.setName(name);
        person.setSex(sex);
        person.setAge(age);
        person.setRank(rank);
        person.setDepartment(department);

        int num = 0;
        num = personSer.addPerson(person);
        if (num > 0){
            try{
                response.sendRedirect("/person?action=queryPerson");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
